<template>
  <el-upload
    class="avatar-uploader"
    :action="uploadApiUrl"
    :show-file-list="false"
    :headers="headers"
    :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload"
  >
    <img v-if="imageUrl" :src="imageUrl" class="avatar" />
    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
  </el-upload>
</template>

<script>
export default {
  name: 'UploadView',

  props: {
    thumb: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      headers: {
        Authorization: localStorage.getItem('token'),
      },

      uploadApiUrl: process.env.VUE_APP_UPLOAD_API_URL,
      uploadBaseUrl: process.env.VUE_APP_UPLOAD_BASE_URL,

      imageUrl: '',
    }
  },

  methods: {
    // 文件
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)

      this.$emit('handleAvatarSuccess', res)
    },
    beforeAvatarUpload(file) {
      const ImageTypeArr = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/svg']

      const isJPG = ImageTypeArr.includes(file.type)
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('请上传图片格式')
        return false
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
        return false
      }
      return isJPG && isLt2M
    },
  },

  watch: {
    thumb(newVal) {
      if (newVal) {
        this.imageUrl = this.uploadBaseUrl + newVal
      }
    },
  },

  created() {},
}
</script>

<style lang="less" scoped>
/* 文件上传 */
/deep/ .el-upload {
  border: 0.1px dashed #d5d5d5;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  background-color: #fafafa;
}

/deep/ .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #7e7e7e;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>
